package com.auxgroup.smarthome.inner.util;

import com.alibaba.fastjson.JSONObject;
import com.auxgroup.smarthome.constant.cache.CachedConsant;
import com.auxgroup.smarthome.enterprise.service.DeviceManageService;
import com.auxgroup.smarthome.enterpriseapi.requestbody.BindAndUnbindBody;
import com.auxgroup.smarthome.enterpriseapi.responsebody.BindAndUnbindStatus;
import com.auxgroup.smarthome.enums.DeviceSourceEnum;
import com.auxgroup.smarthome.inner.entity.DeviceInfoEntity;
import com.auxgroup.smarthome.inner.entity.UserDeviceEntity;
import com.auxgroup.smarthome.inner.repo.DeviceInfoEntityRepo;
import com.auxgroup.smarthome.inner.repo.UserDeviceEntityRepo;
import com.auxgroup.smarthome.redis.config.ObjectRedis;
import com.auxgroup.smarthome.tree.TreeNode;
import com.auxgroup.smarthome.tree.TreeNodeBuilder;
import com.auxgroup.smarthome.utils.common.LOG;
import com.auxgroup.smarthome.web.ApiResponse;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author: laiqiuhua.
 * @Date: 2017/10/24 13:01.
 */
public final class DeviceHelper {

    /**
     * 解绑家人分享下的子用户
     * @param appid
     * @param deviceShareEntity
     */
    public static void unbindSubuserDevice(UserDeviceEntityRepo userDeviceEntityRepo, DeviceInfoEntityRepo deviceInfoEntityRepo, ObjectRedis objectRedis, DeviceManageService deviceManageService, String appid, UserDeviceEntity deviceShareEntity) {
        LOG.info(DeviceHelper.class,"=======================解绑子用户设备开始=========================");
        TreeNode treeNode = new TreeNode(StringUtils.isEmpty(deviceShareEntity.getShareUid())?"root":deviceShareEntity.getShareUid(), deviceShareEntity.getUid(), deviceShareEntity);
        List<TreeNode> treeNodeList = getAllUserDeviceNode(userDeviceEntityRepo, deviceShareEntity.getDeviceId());
        Set<TreeNode> childrenNode = new HashSet<>();
        TreeNodeBuilder.getInstance().findChildNode(treeNode, treeNodeList, childrenNode);
        List<String> uids = new ArrayList<>();
        List<UserDeviceEntity> subShareDevices = childrenNode.stream().map(x-> {
            UserDeviceEntity ud = (UserDeviceEntity) x.getObject();
            ud.setTrash(true);
            uids.add(ud.getUid());
            clearShareRedisByDeviceIdAndUid(objectRedis, ud.getDeviceId(), ud.getUid());
            return ud;
        }).collect(Collectors.toList());
        userDeviceEntityRepo.save(subShareDevices);
        DeviceInfoEntity deviceInfoEntity = deviceInfoEntityRepo.findByMacAndTrashFalse(deviceShareEntity.getMac());
        if (uids.size() > 0) {
            if (deviceInfoEntity.getSource() == DeviceSourceEnum.GIZWITS.getSource()) {
                unbindDeviceByPass(deviceManageService, deviceInfoEntity.getProductKey(), appid, uids, deviceInfoEntity.getDid());
            }
        }
        LOG.info(DeviceHelper.class, "解绑记录==》设备Mac" + deviceInfoEntity.getMac() + "解绑用户：" + Arrays.toString(uids.toArray()));
        LOG.info(DeviceHelper.class,"=======================解绑子用户设备结束=========================");
    }

    public static void unbindDeviceByPass(DeviceManageService deviceManageService, String pk, String appid, List<String> uid, String did) {
        uid.stream().forEach(x-> {
            BindAndUnbindBody bindAndUnbindBody = new BindAndUnbindBody(x, appid, new String[]{did});
            LOG.info(DeviceHelper.class, "开始Enterpriseapi调用-解绑分享设备：参数："+ JSONObject.toJSONString(bindAndUnbindBody));
            ApiResponse<BindAndUnbindStatus> apiResponse = deviceManageService.unbindDevices(pk, bindAndUnbindBody);
            LOG.info(DeviceHelper.class, "结束Enterpriseapi调用"+JSONObject.toJSONString(apiResponse));

        });

    }


    private static List<TreeNode> buildUserDeviceTreeNode(UserDeviceEntityRepo userDeviceEntityRepo, String deviceId) {
        return TreeNodeBuilder.getInstance().buildListToTree(getAllUserDeviceNode(userDeviceEntityRepo, deviceId));
    }

    private static List<TreeNode> getAllUserDeviceNode(UserDeviceEntityRepo userDeviceEntityRepo, String deviceId) {
        List<UserDeviceEntity> userDeviceEntities = userDeviceEntityRepo.findByDeviceIdAndTrashFalse(deviceId);
        List<TreeNode> treeNodes = userDeviceEntities.stream().map(x-> {
            TreeNode treeNode = new TreeNode(StringUtils.isEmpty(x.getShareUid())?"root":x.getShareUid(), x.getUid(), x);
            return treeNode;
        }).collect(Collectors.toList());
        return treeNodes;
    }

    /**
     * 清除设备分享缓存
     * @param deviceId
     * @param uid
     */
    private static void clearShareRedisByDeviceIdAndUid(ObjectRedis objectRedis, String deviceId, String uid) {
        // 删除分享数据缓存
        String key = CachedConsant.DEVICE_SHARE_CACHED_PREFIX + deviceId+ "/" + uid;
        objectRedis.delete(key);
    }

}
